<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="80px">
        <el-form-item label="租户编码" prop="tenantCode">
          <el-input
            v-model="queryParams.tenantCode"
            placeholder="请输入租户编码"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="租户名称" prop="tenantName">
          <el-input
            v-model="queryParams.tenantName"
            placeholder="请输入租户名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="租户类型" prop="tenantType">
          <el-select v-model="queryParams.tenantType" placeholder="租户类型" clearable style="width: 200px">
            <el-option label="企业版" :value="1" />
            <el-option label="个人版" :value="2" />
            <el-option label="试用版" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="租户状态" clearable style="width: 200px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
            <el-option label="试用" :value="2" />
            <el-option label="过期" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="16" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Plus"
            class="toolbar-button is-primary"
            @click="handleAdd"
          >新增租户</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="Delete"
            :disabled="multiple"
            class="toolbar-button is-danger"
            @click="handleDelete"
          >批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            icon="Download"
            class="toolbar-button is-warning"
            @click="handleExport"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            icon="Clock"
            class="toolbar-button is-info"
            @click="handleExpiring"
          >即将到期</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 租户表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="tenantList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="租户编码" align="center" prop="tenantCode" width="120" />
        <el-table-column label="租户名称" align="center" prop="tenantName" :show-overflow-tooltip="true" />
        <el-table-column label="租户类型" align="center" prop="tenantType" width="100">
          <template #default="scope">
            <el-tag :type="getTenantTypeTag(scope.row.tenantType)">
              {{ getTenantTypeName(scope.row.tenantType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="联系人" align="center" prop="contactName" width="100" />
        <el-table-column label="联系邮箱" align="center" prop="contactEmail" width="180" :show-overflow-tooltip="true" />
        <el-table-column label="用户数" align="center" width="100">
          <template #default="scope">
            <span>{{ scope.row.currentUsers }}/{{ scope.row.maxUsers }}</span>
          </template>
        </el-table-column>
        <el-table-column label="存储使用" align="center" width="120">
          <template #default="scope">
            <el-progress 
              :percentage="scope.row.storageUsageRate || 0" 
              :color="getStorageColor(scope.row.storageUsageRate)"
              :show-text="false"
            />
            <div class="storage-text">{{ scope.row.storageUsedFormatted }}/{{ scope.row.storageQuotaFormatted }}</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">
              {{ scope.row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="到期时间" align="center" prop="expireTime" width="180">
          <template #default="scope">
            <span v-if="scope.row.expireTime">{{ parseTime(scope.row.expireTime) }}</span>
            <span v-else>永久</span>
            <el-tag v-if="scope.row.isExpiringSoon" type="warning" size="small" class="ml-2">即将到期</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="info"
                icon="View"
                @click="handleDetail(scope.row)"
                class="table-operation-button is-info"
                size="small"
              >详情</el-button>
              <el-button
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >修改</el-button>
              <el-button
                type="success"
                icon="Setting"
                @click="handleConfig(scope.row)"
                class="table-operation-button is-success"
                size="small"
              >配置</el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button 
                  type="warning" 
                  class="table-operation-button is-warning"
                  size="small"
                >
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="handleToggleStatus" :icon="scope.row.status === 1 ? 'CircleClose' : 'CircleCheck'">
                      {{ scope.row.status === 1 ? '禁用' : '启用' }}
                    </el-dropdown-item>
                    <el-dropdown-item command="handleStats" icon="DataAnalysis">统计信息</el-dropdown-item>
                    <el-dropdown-item command="handleLogs" icon="Document">操作日志</el-dropdown-item>
                    <el-dropdown-item command="handleExportData" icon="Download">导出数据</el-dropdown-item>
                    <el-dropdown-item command="handleDelete" icon="Delete" divided>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改租户对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="tenantFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="租户编码" prop="tenantCode">
              <el-input v-model="form.tenantCode" placeholder="请输入租户编码" :disabled="form.id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租户名称" prop="tenantName">
              <el-input v-model="form.tenantName" placeholder="请输入租户名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="租户类型" prop="tenantType">
              <el-select v-model="form.tenantType" placeholder="请选择租户类型" style="width: 100%">
                <el-option label="企业版" :value="1" />
                <el-option label="个人版" :value="2" />
                <el-option label="试用版" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租户域名" prop="domain">
              <el-input v-model="form.domain" placeholder="请输入租户域名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系人电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人邮箱" prop="contactEmail">
              <el-input v-model="form.contactEmail" placeholder="请输入联系人邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到期时间" prop="expireTime">
              <el-date-picker
                v-model="form.expireTime"
                type="datetime"
                placeholder="选择到期时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最大用户数" prop="maxUsers">
              <el-input-number v-model="form.maxUsers" :min="1" :max="10000" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存储配额(GB)" prop="storageQuotaGB">
              <el-input-number v-model="form.storageQuotaGB" :min="1" :max="1000" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="租户地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入租户地址" />
        </el-form-item>
        
        <!-- 管理员账户信息（仅新增时显示） -->
        <el-divider v-if="!form.id">管理员账户信息</el-divider>
        <el-row v-if="!form.id" :gutter="20">
          <el-col :span="8">
            <el-form-item label="管理员用户名" prop="adminUsername">
              <el-input v-model="form.adminUsername" placeholder="请输入管理员用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="管理员密码" prop="adminPassword">
              <el-input v-model="form.adminPassword" type="password" placeholder="请输入管理员密码" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="管理员邮箱" prop="adminEmail">
              <el-input v-model="form.adminEmail" placeholder="请输入管理员邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 租户详情对话框 -->
    <el-dialog title="租户详情" v-model="detailOpen" width="1000px" append-to-body>
      <TenantDetail v-if="detailOpen" :tenant-id="currentTenantId" @close="detailOpen = false" />
    </el-dialog>

    <!-- 租户配置对话框 -->
    <el-dialog title="租户配置" v-model="configOpen" width="1200px" append-to-body>
      <TenantConfig v-if="configOpen" :tenant-id="currentTenantId" @close="configOpen = false" />
    </el-dialog>

    <!-- 即将到期租户对话框 -->
    <el-dialog title="即将到期的租户" v-model="expiringOpen" width="800px" append-to-body>
      <ExpiringTenants v-if="expiringOpen" @close="expiringOpen = false" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'
import TenantDetail from './components/TenantDetail.vue'
import TenantConfig from './components/TenantConfig.vue'
import ExpiringTenants from './components/ExpiringTenants.vue'
import {
  getTenantPage,
  getTenantDetail,
  createTenant,
  updateTenant,
  deleteTenant,
  deleteTenantBatch,
  updateTenantStatus,
  getExpiringSoonTenants
} from '@/api/tenant'

// 响应式数据
const loading = ref(true)
const open = ref(false)
const detailOpen = ref(false)
const configOpen = ref(false)
const expiringOpen = ref(false)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const tenantList = ref([])
const ids = ref([])
const currentTenantId = ref('')

// 表单引用
const queryFormRef = ref()
const tenantFormRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  tenantCode: undefined,
  tenantName: undefined,
  tenantType: undefined,
  status: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  tenantCode: undefined,
  tenantName: undefined,
  tenantType: 1,
  domain: undefined,
  contactName: undefined,
  contactPhone: undefined,
  contactEmail: undefined,
  address: undefined,
  expireTime: undefined,
  maxUsers: 100,
  storageQuotaGB: 10,
  adminUsername: undefined,
  adminPassword: undefined,
  adminEmail: undefined
})

// 表单验证规则
const rules = reactive({
  tenantCode: [
    { required: true, message: '租户编码不能为空', trigger: 'blur' },
    { min: 3, max: 50, message: '租户编码长度必须在3到50之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '租户编码只能包含字母、数字、下划线和横线', trigger: 'blur' }
  ],
  tenantName: [
    { required: true, message: '租户名称不能为空', trigger: 'blur' },
    { min: 2, max: 100, message: '租户名称长度必须在2到100之间', trigger: 'blur' }
  ],
  tenantType: [
    { required: true, message: '租户类型不能为空', trigger: 'change' }
  ],
  contactName: [
    { required: true, message: '联系人姓名不能为空', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '联系人邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  maxUsers: [
    { required: true, message: '最大用户数不能为空', trigger: 'blur' },
    { type: 'number', min: 1, message: '最大用户数必须大于0', trigger: 'blur' }
  ],
  storageQuotaGB: [
    { required: true, message: '存储配额不能为空', trigger: 'blur' },
    { type: 'number', min: 1, message: '存储配额必须大于0', trigger: 'blur' }
  ],
  adminUsername: [
    { required: true, message: '管理员用户名不能为空', trigger: 'blur' },
    { min: 3, max: 20, message: '管理员用户名长度必须在3到20之间', trigger: 'blur' }
  ],
  adminPassword: [
    { required: true, message: '管理员密码不能为空', trigger: 'blur' },
    { min: 6, max: 20, message: '管理员密码长度必须在6到20之间', trigger: 'blur' }
  ],
  adminEmail: [
    { required: true, message: '管理员邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})

// 获取租户列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getTenantPage(queryParams)
    tenantList.value = response.data.records
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取租户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加租户'
}

// 修改按钮操作
const handleUpdate = async (row) => {
  reset()
  const tenantId = row.id || ids.value[0]
  try {
    const response = await getTenantDetail(tenantId)
    const tenant = response.data
    Object.assign(form, {
      ...tenant,
      storageQuotaGB: Math.round(tenant.storageQuota / (1024 * 1024 * 1024))
    })
    open.value = true
    title.value = '修改租户'
  } catch (error) {
    ElMessage.error('获取租户详情失败')
  }
}

// 详情按钮操作
const handleDetail = (row) => {
  currentTenantId.value = row.id
  detailOpen.value = true
}

// 配置按钮操作
const handleConfig = (row) => {
  currentTenantId.value = row.id
  configOpen.value = true
}

// 删除按钮操作
const handleDelete = async (row) => {
  const tenantIds = row?.id ? [row.id] : ids.value
  const tenantNames = row?.tenantName ? [row.tenantName] : tenantList.value.filter(item => tenantIds.includes(item.id)).map(item => item.tenantName)

  try {
    await ElMessageBox.confirm(
      `是否确认删除租户"${tenantNames.join('、')}"？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (tenantIds.length === 1) {
      await deleteTenant(tenantIds[0])
    } else {
      await deleteTenantBatch(tenantIds)
    }

    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 导出按钮操作
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 即将到期按钮操作
const handleExpiring = () => {
  expiringOpen.value = true
}

// 下拉菜单操作
const handleCommand = async (command, row) => {
  switch (command) {
    case 'handleToggleStatus':
      await handleToggleStatus(row)
      break
    case 'handleStats':
      handleStats(row)
      break
    case 'handleLogs':
      handleLogs(row)
      break
    case 'handleExportData':
      handleExportData(row)
      break
    case 'handleDelete':
      await handleDelete(row)
      break
  }
}

// 切换状态
const handleToggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'

  try {
    await ElMessageBox.confirm(
      `确认要${statusText}租户"${row.tenantName}"吗？`,
      '系统提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await updateTenantStatus(row.id, newStatus)
    ElMessage.success(`${statusText}成功`)
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${statusText}失败`)
    }
  }
}

// 统计信息
const handleStats = (row) => {
  ElMessage.info('统计信息功能开发中...')
}

// 操作日志
const handleLogs = (row) => {
  ElMessage.info('操作日志功能开发中...')
}

// 导出数据
const handleExportData = (row) => {
  ElMessage.info('导出数据功能开发中...')
}

// 提交表单
const submitForm = () => {
  tenantFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const formData = {
          ...form,
          storageQuota: form.storageQuotaGB * 1024 * 1024 * 1024 // 转换为字节
        }

        if (form.id) {
          await updateTenant(formData)
          ElMessage.success('修改成功')
        } else {
          await createTenant(formData)
          ElMessage.success('新增成功')
        }

        open.value = false
        getList()
      } catch (error) {
        ElMessage.error(form.id ? '修改失败' : '新增失败')
      }
    }
  })
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: undefined,
    tenantCode: undefined,
    tenantName: undefined,
    tenantType: 1,
    domain: undefined,
    contactName: undefined,
    contactPhone: undefined,
    contactEmail: undefined,
    address: undefined,
    expireTime: undefined,
    maxUsers: 100,
    storageQuotaGB: 10,
    adminUsername: undefined,
    adminPassword: undefined,
    adminEmail: undefined
  })
  tenantFormRef.value?.resetFields()
}

// 获取租户类型名称
const getTenantTypeName = (type) => {
  const typeMap = {
    1: '企业版',
    2: '个人版',
    3: '试用版'
  }
  return typeMap[type] || '未知'
}

// 获取租户类型标签
const getTenantTypeTag = (type) => {
  const tagMap = {
    1: 'primary',
    2: 'success',
    3: 'warning'
  }
  return tagMap[type] || 'info'
}

// 获取状态标签
const getStatusTag = (status) => {
  const tagMap = {
    0: 'danger',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return tagMap[status] || 'info'
}

// 获取存储使用率颜色
const getStorageColor = (rate) => {
  if (rate >= 90) return '#f56c6c'
  if (rate >= 70) return '#e6a23c'
  return '#67c23a'
}

// 组件挂载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;

  .el-form {
    .el-form-item {
      margin-bottom: 12px;
    }
  }
}

.toolbar-card {
  margin-bottom: 20px;

  .toolbar-button {
    margin-right: 10px;

    &.is-primary {
      background-color: #409eff;
      border-color: #409eff;

      &:hover {
        background-color: #66b1ff;
        border-color: #66b1ff;
      }
    }

    &.is-danger {
      background-color: #f56c6c;
      border-color: #f56c6c;

      &:hover {
        background-color: #f78989;
        border-color: #f78989;
      }
    }

    &.is-warning {
      background-color: #e6a23c;
      border-color: #e6a23c;

      &:hover {
        background-color: #ebb563;
        border-color: #ebb563;
      }
    }

    &.is-info {
      background-color: #909399;
      border-color: #909399;

      &:hover {
        background-color: #a6a9ad;
        border-color: #a6a9ad;
      }
    }
  }
}

.table-operation-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;

  .table-operation-button {
    &.is-info {
      background-color: #909399;
      border-color: #909399;
      color: white;

      &:hover {
        background-color: #a6a9ad;
        border-color: #a6a9ad;
      }
    }

    &.is-primary {
      background-color: #409eff;
      border-color: #409eff;
      color: white;

      &:hover {
        background-color: #66b1ff;
        border-color: #66b1ff;
      }
    }

    &.is-success {
      background-color: #67c23a;
      border-color: #67c23a;
      color: white;

      &:hover {
        background-color: #85ce61;
        border-color: #85ce61;
      }
    }

    &.is-warning {
      background-color: #e6a23c;
      border-color: #e6a23c;
      color: white;

      &:hover {
        background-color: #ebb563;
        border-color: #ebb563;
      }
    }

    &.is-danger {
      background-color: #f56c6c;
      border-color: #f56c6c;
      color: white;

      &:hover {
        background-color: #f78989;
        border-color: #f78989;
      }
    }
  }
}

.storage-text {
  font-size: 12px;
  color: #606266;
  margin-top: 2px;
}

.dialog-footer {
  text-align: right;

  .el-button {
    margin-left: 10px;
  }
}

.mb8 {
  margin-bottom: 8px;
}

.ml-2 {
  margin-left: 8px;
}

:deep(.el-table) {
  .el-table__cell {
    padding: 8px 0;
  }
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-progress-bar__outer) {
  height: 8px;
  border-radius: 4px;
}

:deep(.el-progress-bar__inner) {
  border-radius: 4px;
}
</style>
